<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>车位管理</title>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.js"></script>
    <link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css">
    <script src="/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">

    <el-card shadow="always">
        <div slot="header">
            <span>车位管理</span>
        </div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>社区物业管理</el-breadcrumb-item>
            <el-breadcrumb-item>基础信息管理</el-breadcrumb-item>
            <el-breadcrumb-item>车位管理</el-breadcrumb-item>
        </el-breadcrumb>
    </el-card>

    <el-card shadow="always">
        <el-form :inline="true" :model="param" class="demo-form-inline" size="small">
            <el-form-item label="车位编号">
                <el-input v-model="param.numbers" placeholder="请输入车位号" size="medium"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit" icon="el-icon-search" size="medium">查询</el-button>
                <el-button type="success" @click="showDialog" icon="el-icon-circle-plus" size="medium">添加</el-button>
            </el-form-item>
        </el-form>

        <el-table
                ref="multipleTable"
                :data="pageBean.data"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>

            <el-table-column
                    prop="numbers"
                    label="车位号"
                    width="180">
            </el-table-column>

            <el-table-column
                    prop="username"
                    label="业主姓名"
                    width="180">
            </el-table-column>

            <el-table-column
                    prop="tel"
                    label="业主电话"
                    width="180">
            </el-table-column>

            <el-table-column
                    prop="status"
                    label="使用状态"
                    width="100">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'primary' : 'success'">
                        {{scope.row.status === 1 ? '使用' : '闲置'}}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button
                                size="mini" icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger" icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination style="margin-top: 10px"
                       background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="pageBean.current"
                       :page-sizes="[5, 10, 15]"
                       :page-size="pageBean.size"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="pageBean.count">
        </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
            title="车位管理"
            :visible.sync="dialogVisible"
            width="550px"
            center>

        <!-- 表单 -->
        <el-form :model="parkingForm" :rules="rules" ref="parkingForm" label-width="100px">
            <!-- prop绑定rules中验证规则 -->
            <el-form-item label="车位编号" prop="numbers">
                <el-input v-model="parkingForm.numbers" placeholder="请输入车位编号" style="width:200px"></el-input>
            </el-form-item>

            <el-form-item label="关联业主" prop="ownerId">
                <!-- 远程加载业主 -->
                <el-select
                        v-model="parkingForm.ownerId" style="width:200px"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        placeholder="请输入业主名字"
                        :remote-method="remoteMethod"
                        :loading="loading">
                    <!-- options是所有的业主 id是主键 username是业主名字-->
                    <el-option
                            v-for="item in options"
                            :key="item.id"
                            :label="item.username"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="备注信息" prop="status">
                <el-switch
                        v-model="parkingForm.status"
                        active-text="使用"
                        inactive-text="闲置"
                        :active-value="1"
                        :inactive-value="0">
                </el-switch>
            </el-form-item>

            <el-form-item label="备注信息" prop="remarks">
                <el-input type="textarea" v-model="parkingForm.remarks" placeholder="备注可选"
                          style="width:350px"></el-input>
            </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('parkingForm')">确定</el-button>
                <el-button @click="resetForm('parkingForm')">取消</el-button>
              </span>

    </el-dialog>

</div>
<script type="text/javascript">
    new Vue({
        el: "#app",
        data() {
            //判断车位号是否存在，参数：规则对象，要验证的值，是否验证成功的回调函数
            let validateNumberExists = (rule, value, callback) => {
                if (this.addModel) {
                    axios.get(`/parking/isParkingExists?numbers=${value}`).then(resp => {
                        //返回true或false
                        if (resp.data) {
                            callback(new Error('车位号已经存在'));
                        } else {
                            callback();
                        }
                    });
                } else {
                    //通过验证
                    callback();
                }
            }
            return {
                //添加模式或编辑模式
                addModel: true,
                //一页数据对象
                pageBean: {},
                //提交参数对象
                param: {
                    numbers: '',
                    page: 1,
                    size: 5
                },
                multipleSelection: [],
                //是否显示对话框
                dialogVisible: false,
                parkingForm: {
                    status: 0
                },  //表单数据
                loading: false,  //是否远程加载
                options: [],  //业主下拉选项列表
                //验证规则
                rules: {
                    numbers: [
                        {required: true, message: '车位编号不能为空', trigger: 'blur'},
                        {pattern: /^[a-zA-Z]\d-\d{3}$/, message: '车位编号格式错误', trigger: 'blur'},
                        //自定义验证器
                        {validator: validateNumberExists, trigger: 'blur'}
                    ],
                    ownerId: [
                        {required: true, message: '业主必须选择', trigger: 'change'}
                    ]
                }
            }
        },
        methods: {
            //显示对话框
            showDialog() {
                //添加模式
                this.addModel = true;
                //显示窗口
                this.dialogVisible = true;
                //清空
                this.ruleForm = {
                    numbers: '',
                    ownerId: null,
                    status: 0,
                    remarks: ''
                };
                //等待DOM创建完成才执行
                this.$nextTick(() => {
                    //表单重置，清除数据和验证规则
                    this.$refs.parkingForm.resetFields();
                });
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //编辑按钮
            handleEdit(index, row) {
                //修改成编辑模式
                this.addModel = false;
                //对象的复制
                let data = Object.assign({}, row);
                //获取数据
                this.parkingForm = data;
                //显示窗口
                this.dialogVisible = true;
                //等待DOM创建完成才执行
                this.$nextTick(() => {
                    //清除验证规则
                    this.$refs.parkingForm.clearValidate();
                });
                //处理业主下拉选项，将现有的值赋值给options
                this.options = [{
                    id: data.ownerId,
                    username: data.username
                }];
            },
            handleDelete(index, row) {
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.param.size = val;
                this.findByPage();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.param.page = val;
                this.findByPage();
            },
            onSubmit() {
            },
            //分页查询
            findByPage() {
                axios.post('/parking/findByPage', this.param).then(resp => {
                    this.pageBean = resp.data;
                });
            },
            //添加
            add() {
                axios.post('/parking/add', this.parkingForm).then(resp => {
                    this.$message.success('添加车位成功');
                    //关闭窗口
                    this.dialogVisible = false;
                }).catch(error => {
                    this.$message.error(`添加车位失败：${error.message}`);
                }).finally(() => {
                    this.findByPage();
                });
            },
            //修改
            update() {
                axios.post('/parking/update', this.parkingForm).then(resp => {
                    this.$message.success('修改车位成功');
                    //关闭窗口
                    this.dialogVisible = false;
                }).catch(error => {
                    this.$message.error(`修改车位失败：${error.message}`);
                }).finally(() => {
                    this.findByPage();
                });
            },
            //确定按钮
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //判断是修改还是添加
                        if (this.addModel) {
                            this.add();
                        } else {
                            this.update();
                        }
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
            },
            //远程加载的方法, query输入的字符串 (业主名字)
            remoteMethod(query) {
                console.log("输入名字：" + query);
                //不为空才去访问服务器
                if (query.trim() !== '') {
                    //远程加载
                    this.loading = true;
                    //后台通过业主名字模糊查询
                    axios.get(`/owner/findByOwners?username=${query}`).then(resp => {
                        //放在options中
                        this.options = resp.data;
                    }).finally(() => {
                        this.loading = false;
                    });
                }
            }
        },
        mounted() {
            this.findByPage();
        }
    });
</script>
</body>
</html>